//
//  WKWithdrawBiVM.m
//  LLWallet
//
//  Created by wangfei on 2025/9/14.
//

#import "WKWithdrawBiVM.h"

#import "FFWithdrawAmountInputCell.h"
#import "FFWithdrawContactsCell.h"
#import "FFServicerListVC.h"
#import "FFBankcardListVC.h"
#import "FFWalletManager.h"
#import "FFWalletConst.h"
#import <sys/utsname.h>
#import "WKBiAddressListVC.h"

@interface WKWithdrawBiVM ()

@property(nonatomic,strong) FFWithdrawConfig *config;
// 被选中的银行卡信息
@property(nonatomic,strong) WKBiAddressListResp *coinItem;

@property(nonatomic,copy) NSString *rate;

@property(nonatomic,strong) NSNumber *withdrawAmount; // 输入的提现金额

@end

@implementation WKWithdrawBiVM

- (NSArray<NSDictionary *> *)tableSectionMaps {
    if(!self.config) {
        return nil;
    }
    NSString *remark = [NSString stringWithFormat:LLang(@"可用余额 ¥%@"),[WKMoneyUtil penny2Yuan:self.config.usableAmount]];
    if (self.rate){
        remark = [NSString stringWithFormat:LLang(@"可用余额 ¥%@,(当前汇率:%@)"),[WKMoneyUtil penny2Yuan:self.config.usableAmount],self.rate];
    }
    __weak typeof(self) weakSelf = self;
    return @[
        @{
            @"height": @(20.0),
            @"items": @[
                    @{
                        @"class": WKLabelItemModel.class,
                        @"label": LLang(@"到账地址"),
                        @"value": self.coinItem.address?[NSString stringWithFormat:@"%@(%@)",self.coinItem.address,[self.coinItem.address substringFromIndex:self.coinItem.address.length-4]]:LLang(@"请选择到账地址"),
                        @"onClick": ^{
                            WKBiAddressListVC *vc = [WKBiAddressListVC new];
                            vc.confirmBlock = ^(WKBiAddressListResp * _Nonnull item) {
                                weakSelf.coinItem = item;
                                [weakSelf getRate];
                            };
                            [[WKNavigationManager shared] pushViewController:vc animated:YES];
                        },
                        
                    }
            ],
        },
        @{
            @"height": @(20.0),
            @"items": @[
                    @{
                        @"class": FFWithdrawAmountInputModel.class,
                        @"value": self.withdrawAmount?[NSString stringWithFormat:@"%0.2f",self.withdrawAmount.floatValue]:@"",
                        @"remark":remark,
                        @"onAllWithdraw": ^{
                            weakSelf.withdrawAmount = [WKMoneyUtil penny2Yuan:self.config.usableAmount];
                            [weakSelf reloadData];
                        },
                        @"onChange":^(NSString *value){
                            weakSelf.withdrawAmount = @(value.floatValue);
                        }
                    }
            ],
        },
        @{
             @"height":@(40.0f),
             @"items":@[
                     @{
                         @"class":WKButtonItemModel2.class,
                         @"title": LLang(@"提现"),
                         @"onPressed":^{
                             if (!self.coinItem){
                                 [[WKNavigationManager shared].topViewController.view showHUDWithHide:LLang(@"请选择提现币种")];
                                 return;
                             }
                             if (!self.withdrawAmount){
                                 [[WKNavigationManager shared].topViewController.view showHUDWithHide:LLang(@"提现金额不能等于或小于0！")];
                                 return;
                             }
                             NSInteger withdrawAmountPen =   [WKMoneyUtil yuan2Penny:self.withdrawAmount].integerValue;
                             if(withdrawAmountPen<=0) {
                                 [[WKNavigationManager shared].topViewController.view showHUDWithHide:LLang(@"提现金额不能等于或小于0！")];
                                 return;
                             }
                             if(withdrawAmountPen>self.config.usableAmount.integerValue) {
                                [[WKNavigationManager shared].topViewController.view showHUDWithHide:LLang(@"输入金额超过零钱余额！")];
                                 return;
                             }
                             
                             [[FFWalletManager shared] ff_getPayToken:withdrawAmountPen item:LIMPayItemWithdraw remark:LLang(@"提现") callback:^(NSString * _Nonnull payToken) {
                                 [[WKNavigationManager shared].topViewController.view showHUD];
                                 [weakSelf requestWidthdraw:payToken].then(^{
                                     [[WKNavigationManager shared].topViewController.view hideHud];
                                     [[WKNavigationManager shared] popViewControllerAnimated:YES];
                                     [[NSNotificationCenter defaultCenter] postNotificationName:LIM_NOTIFY_WALLET_REFRESH object:nil];
                                     
                                 }).catch(^(NSError *error){
                                     [[WKNavigationManager shared].topViewController.view switchHUDError:error.domain];
                                 });
                             }];
                         }
                     },
             ]
        },
        @{
            @"height": @(10.0),
            @"items": @[
                    @{
                        @"class": WKLabelModel.class,
                        @"text": [self composeRemark],
                    }
            ],
        },
        @{
            @"height": @(0.01),
            @"items": @[
                    @{
                        @"class": FFWithdrawContactsModel.class,
                        @"tip": LLang(@"如2小时后未到账，请联系客服"),
                        @"onContactClick":^{
                            [[WKNavigationManager shared] pushViewController:[FFServicerListVC new] animated:YES];
                        }
                    }
            ],
        },
    ];
}

-(NSString*) composeRemark {
    NSString *explainStr = LLang(@"提现说明:");
    if(self.config.explain && self.config.explain.count>0) {
        for (NSString *exp in self.config.explain) {
            explainStr = [NSString stringWithFormat:@"%@\n%@",explainStr,exp];
        }
    }
    return explainStr;
}
- (void)getRate{
    
    __weak typeof(self) weakSelf = self;
    [[WKAPIClient sharedClient] GET:[NSString stringWithFormat:@"udun/coin_types/%ld/rate",self.coinItem._id] parameters:nil].then(^(NSDictionary *dic){
        if ([dic isKindOfClass:[NSDictionary class]]){
            NSDictionary *coin_rate = dic[@"coin_rate"];
            weakSelf.rate = coin_rate[@"rate"];
        }
        [weakSelf reloadData];
    }).catch(^(NSError *error){
        [weakSelf reloadData];
    });
}



- (void)requestData:(void (^)(NSError * _Nullable))complete {
    __weak typeof(self) weakSelf = self;
    [[WKAPIClient sharedClient] GET:@"impay/withdrawconfig" parameters:nil model:FFWithdrawConfig.class].then(^(FFWithdrawConfig *config){
        weakSelf.config = config;
        complete(nil);
    }).catch(^(NSError *error){
        complete(error);
    });
}

// 请求提现
-(AnyPromise*) requestWidthdraw:(NSString*)payToken {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    return [[WKAPIClient sharedClient] POST:@"impay/withdraw" parameters:@{
        @"pay_token": payToken,
        @"amount":[WKMoneyUtil yuan2Penny:self.withdrawAmount],
        @"account_type": @"UDUN", // 银行卡提现
        @"account": self.coinItem.address,
//        @"bankcard_id": @(self.bankcard._id),
        @"device_os": [NSString stringWithFormat:@"%@ %@ %@",deviceModel,[UIDevice currentDevice].systemName,[UIDevice currentDevice].systemVersion],
        @"bundle_id":[[NSBundle mainBundle] bundleIdentifier],
    }];
}

@end

